package com.tensquare.article.service;


import com.tensquare.article.pojo.Comment;
import com.tensquare.article.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;


import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Queue;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    //ID生成器
    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Comment> findAll() {
        return commentRepository.findAll();
    }

    public Comment findById(String commentId) {
        Optional<Comment> optionalComment = commentRepository.findById(commentId);

        if(optionalComment.isPresent()){
            return optionalComment.get();
        }
        return null;
    }

    public void save(Comment comment) {
        //使用分布式id生成器
        String id = idWorker.nextId()+"";
        comment.set_id(id);
        //初始化数据
        comment.setThumbup(0);
        comment.setPublishdate(new Date());

        //保存数据
        commentRepository.save(comment);
    }

    public void updateById(Comment comment) {
        commentRepository.save(comment);
    }

    public void deleteById(String commentId) {
        commentRepository.deleteById(commentId);
    }

    public List<Comment> findByArticleId(String articleId) {
        return commentRepository.findByArticleid(articleId);
    }

    public void thump(String commentId) {
//        //根据评论ID查询数据
//        Comment comment = commentRepository.findById(commentId).get();
//        //根据评论数据+1
//        comment.setThumbup(comment.getThumbup()+1);
//        //保存数据
//        commentRepository.save(comment);

        //点赞功能优化
        Query query=new Query();
        //修改条件
        query.addCriteria(Criteria.where("_id").is(commentId));
        //修改数值
        Update update=new Update();
        update.inc("thumbup",1);

        //集合名
        mongoTemplate.updateFirst(query,update,"comment");

    }
}
